<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="theme-color" content="#4CAF50">
    <title>批量上传股票图片</title>
    <link rel="stylesheet" href="/css/style.css">
</head>
<body>
    <div class="container">
        <div class="nav-links">
            <a href="/">训练页面</a>
            <a href="/upload">批量上传</a>
        </div>

        <h2>批量上传图片</h2>

        <div class="upload-section">
            <div class="type-selector">
                <h3>选择类型：</h3>
                <label>
                    <input type="radio" name="imageType" value="UP">
                    <span>看涨图片</span>
                </label>
                <label>
                    <input type="radio" name="imageType" value="DOWN">
                    <span>看跌图片</span>
                </label>
            </div>

            <div class="upload-controls">
                <input type="file" id="fileInput" multiple accept="image/*" style="display: none;">
                <div class="button-group">
                    <button class="btn btn-primary" onclick="document.getElementById('fileInput').click()">
                        选择图片
                    </button>
                    <button class="btn btn-primary" id="uploadBtn" onclick="uploadFiles()" disabled>
                        开始上传
                    </button>
                </div>
            </div>

            <div class="upload-stats">
                <div>已选择: <span id="fileCount">0</span> 个文件</div>
                <div>总大小: <span id="totalSize">0 B</span></div>
                <div>上传进度: <span id="uploadProgress">0%</span></div>
            </div>
        </div>

        <div id="status" class="status"></div>
        <div id="fileList" class="file-list"></div>
    </div>

    <script>
        // 全局变量和常量
        const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
        const MAX_TOTAL_SIZE = 50 * 1024 * 1024; // 50MB
        const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/jpg'];
        
        let selectedFiles = new Map();
        let isUploading = false;

        // DOM 元素
        const fileInput = document.getElementById('fileInput');
        const fileList = document.getElementById('fileList');
        const uploadBtn = document.getElementById('uploadBtn');
        const fileCountSpan = document.getElementById('fileCount');
        const totalSizeSpan = document.getElementById('totalSize');
        const uploadProgress = document.getElementById('uploadProgress');

        // 文件选择处理
        fileInput.addEventListener('change', (e) => {
            if (isUploading) return;

            const newFiles = Array.from(e.target.files);
            let totalSize = Array.from(selectedFiles.values())
                .reduce((sum, file) => sum + file.size, 0);

            for (const file of newFiles) {
                // 文件大小检查
                if (file.size > MAX_FILE_SIZE) {
                    showStatus(`文件 ${file.name} 超过10MB限制`, false);
                    continue;
                }

                // 文件类型检查
                if (!ALLOWED_TYPES.includes(file.type)) {
                    showStatus(`文件 ${file.name} 不是支持的图片格式`, false);
                    continue;
                }

                // 总大小检查
                if (totalSize + file.size > MAX_TOTAL_SIZE) {
                    showStatus('总文件大小超过50MB限制', false);
                    break;
                }

                totalSize += file.size;
                selectedFiles.set(file.name, file);
                createFileItem(file);
            }

            updateStats();
            checkUploadability();
            fileInput.value = ''; // 清空input，允许重复选择
        });

        // 创建文件预览
        function createFileItem(file) {
            const reader = new FileReader();
            reader.onload = (e) => {
                const div = document.createElement('div');
                div.className = 'file-item';
                div.innerHTML = `
                    <img src="${e.target.result}" alt="${file.name}">
                    <div class="file-info">
                        <div class="file-name">${file.name}</div>
                        <div class="file-size">${formatFileSize(file.size)}</div>
                    </div>
                    <button class="remove-file" onclick="removeFile('${file.name}')" 
                            ${isUploading ? 'disabled' : ''}>&times;</button>
                `;
                fileList.appendChild(div);
            };
            reader.readAsDataURL(file);
        }

        // 移除文件
        function removeFile(fileName) {
            if (isUploading) return;
            
            selectedFiles.delete(fileName);
            const items = fileList.getElementsByClassName('file-item');
            for (let item of items) {
                if (item.querySelector('.file-name').textContent === fileName) {
                    item.remove();
                    break;
                }
            }
            updateStats();
            checkUploadability();
        }

        // 更新统计信息
        function updateStats() {
            const count = selectedFiles.size;
            const totalSize = Array.from(selectedFiles.values())
                .reduce((sum, file) => sum + file.size, 0);
            
            fileCountSpan.textContent = count;
            totalSizeSpan.textContent = formatFileSize(totalSize);
        }

        // 检查是否可以上传
        function checkUploadability() {
            const hasFiles = selectedFiles.size > 0;
            const hasType = document.querySelector('input[name="imageType"]:checked') !== null;
            uploadBtn.disabled = isUploading || !(hasFiles && hasType);
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 显示状态消息
        function showStatus(message, isSuccess, duration = 3000) {
            const status = document.getElementById('status');
            status.textContent = message;
            status.className = 'status ' + (isSuccess ? 'success' : 'error');
            status.style.display = 'block';
            
            if (!isSuccess || duration > 0) {
                setTimeout(() => {
                    status.style.display = 'none';
                }, duration);
            }
        }

        // 上传文件
        async function uploadFiles() {
            const type = document.querySelector('input[name="imageType"]:checked')?.value;
            if (!type) {
                showStatus('请选择图片类型', false);
                return;
            }

            if (selectedFiles.size === 0) {
                showStatus('请选择要上传的图片', false);
                return;
            }

            try {
                isUploading = true;
                uploadBtn.disabled = true;
                document.querySelectorAll('.remove-file').forEach(btn => btn.disabled = true);

                const formData = new FormData();
                selectedFiles.forEach(file => {
                    formData.append('images', file);
                });
                formData.append('type', type);

                const response = await fetch('/api/upload', {
                    method: 'POST',
                    body: formData
                });

                if (!response.ok) {
                    throw new Error(await response.text());
                }

                showStatus(`成功上传 ${selectedFiles.size} 个文件！`, true);
                
                // 清空选择
                selectedFiles.clear();
                fileList.innerHTML = '';
                document.querySelector('input[name="imageType"]:checked').checked = false;
                updateStats();
                
                // 延迟2秒后刷新页面
                setTimeout(() => {
                    window.location.reload();
                }, 2000);

            } catch (error) {
                showStatus('上传失败：' + error.message, false);
            } finally {
                isUploading = false;
                uploadBtn.disabled = false;
                document.querySelectorAll('.remove-file').forEach(btn => btn.disabled = false);
                uploadProgress.textContent = '0%';
            }
        }

        // 类型选择监听
        document.querySelectorAll('input[name="imageType"]').forEach(radio => {
            radio.addEventListener('change', checkUploadability);
        });

        // 页面卸载前确认
        window.addEventListener('beforeunload', (e) => {
            if (selectedFiles.size > 0 && !isUploading) {
                e.preventDefault();
                e.returnValue = '您有未上传的文件，确定要离开吗？';
            }
        });
    </script>
</body>
</html> 